<?php
require_once('lib/ftree_utils.php');
include('lib/adodb-time.inc.php');
include('lib/getLoginID.php');
require_once "HTML/Template/IT.php";

function writeParent($id, $var)
{
	global $tpl,$link;

	$query = "SELECT * FROM `person` WHERE `id` = $id";
	$result = mysql_query($query,$link) or die("Query failed : " . mysql_error());
	$data = mysql_fetch_array($result, MYSQL_ASSOC);
	
	$full = formatName($data['first'], $data['middle'], $data['last'], $data['suffix'], $data['nick'], "fmls");
	$dates = "";
	$dob = formatDate($data['dob'],"short");
	$dod = formatDate($data['dod'],"short");
	if ($dob != "") {
		$dates = "$dob-";
	}
	if ($dod != "") {
		if ($dob == "") {
			$dates = "-";
		}
		$dates .= "$dod";
	}
	$tpl->setVariable($var, $full);
	$tpl->setVariable("${var}ID", $data['id']);
	$tpl->setVariable("${var}Dates", $dates);

	// Only used for Adding. Editing is done from edit person form.
	if ($data['id'] == "") { enableAddParent($var); }
	
	mysql_free_result($result);
}

function writeKids($fID, $mID, $var)
{
	global $tpl,$link;

        $query = "SELECT * FROM `person` WHERE `father` = $fID AND `mother` = $mID ORDER BY `dob` ASC";
        $result = mysql_query($query,$link) or die("Query failed : " . mysql_error());

        while ($data = mysql_fetch_array($result, MYSQL_ASSOC)) {

        $full = formatName($data['first'], $data['middle'], $data['last'], $data['suffix'], $data['nick'], "fm");
        $dob  = formatDate($data['dob'],"short");
		$tpl->setCurrentBlock($var) ;
		$tpl->setVariable($var, $full) ;
		$tpl->setVariable("${var}DOB", $dob) ;
		$tpl->setVariable("${var}ID", $data['id']) ;
		$tpl->parseCurrentBlock($var);

        }
        mysql_free_result($result);
}

function enableEdit ($id)
{
	// Top level -- edit the person
	global $edit_users, $tpl;

	//$html = "$edit_users<br>${_SERVER['REMOTE_USER']}\n";
	if (preg_match("/${_SERVER['REMOTE_USER']}/",$edit_users)) {
	//if (preg_match("/test/",$edit_users)) {
		$html = '<p align="center"><a href="person.php?id=' . $id . '&mode=w"><img border="0" src="icons/edit_male.gif" alt="Edit"></a></p>';
		$tpl->setVariable("EditBtn", $html) ;
	}
}

function enableDBEdit ($id)
{
	// By the person's ID, take me to the person's entry in the DB
	global $edit_users, $tpl;

	if (preg_match("/${_SERVER['REMOTE_USER']}/",$edit_users)) {
		// $html = '<a title="Edit person in DB" href="http://www.stanley5.com/lib/phpmyadmin/tbl_change.php?lang=en-iso-8859-1&server=1&db=ftree&table=person&pos=0&session_max_rows=30&disp_direction=horizontal&repeat_cells=100&dontlimitchars=0&primary_key=+%60id%60+%3D+%27' . $id . '%27&sql_query=SELECT++%2A+%0AFROM++%60person%60+%0AWHERE+1++AND++%60id%60++%3D' . $id . '&goto=sql.php" target="_blank"><img border="0" src="icons/edit_male.gif" alt="Edit person in DB"></a> ';
		$html = '<a title="Edit person in DB" href="/lib/phpmyadmin/tbl_change.php?db=ftree&table=person&ftree=edit_user&primary_key=+%60id%60+%3D+%27' . $id . '%27&goto=sql.php" target="_blank"><img border="0" src="icons/edit_male.gif" alt="Edit person in DB"></a> ';
		$tpl->setVariable("dbBtn", $html) ;
	}
}

function enableAddChild ($id,$fid,$mid)
{
	global $edit_users, $tpl;

	if (preg_match("/${_SERVER['REMOTE_USER']}/",$edit_users)) {
		$html = '<a href="person.php?id=' . $id . '&mode=a&rel=c&fid=' . $fid . '&mid=' . $mid . '"><img border="0" src="icons/add_male.gif" alt="Add Child"></a>';
		$tpl->setVariable("AddChildBtn", $html) ;
	}
}

function enableAddParent ($whPar)
{
	global $edit_users, $tpl, $id;

	if (preg_match("/${_SERVER['REMOTE_USER']}/",$edit_users)) {
		if ($whPar == "Father") { $whP = "f"; } else { $whP = "m"; }
		$html = '<a href="person.php?id=' . $id . '&mode=a&rel=' . $whP . '"><img border="0" src="icons/add_male.gif" alt="Add '. $whPar . '"></a>';
		//$html = '<a title="Add ' . $whPar . ' in DB" href="http://www.stanley5.com/lib/phpmyadmin/tbl_change.php?lang=en-iso-8859-1&server=1&db=ftree&table=person&pos=0&session_max_rows=30&disp_direction=horizontal&repeat_cells=100&dontlimitchars=0&primary_key=+%60id%60+%3D+%27' . $id . '%27&sql_query=SELECT++%2A+%0AFROM++%60person%60+%0AWHERE+1++AND++%60id%60++%3D' . $id . '&goto=sql.php" target="_blank"><img border="0" src="icons/edit_sm.gif" alt="Add new ' . $whPar . '"></a>';
		$tpl->setVariable("Add" . $whPar . "NewBtn", $html) ;
	}
}

function enableAddSpouse ()
{
	# NOT YET WORKING - spouse section doesn't even show if no spouse
	# not yet called from anywhere
	
	global $edit_users, $tpl, $id;

	if (preg_match("/${_SERVER['REMOTE_USER']}/",$edit_users)) {
		$html = '<a href="person.php?id=' . $id . '&mode=a&rel=s"><img border="0" src="icons/add_male.gif" alt="Add Spouse"></a>';
		//$html = '<a title="Add ' . $whPar . ' in DB" href="http://www.stanley5.com/lib/phpmyadmin/tbl_change.php?lang=en-iso-8859-1&server=1&db=ftree&table=person&pos=0&session_max_rows=30&disp_direction=horizontal&repeat_cells=100&dontlimitchars=0&primary_key=+%60id%60+%3D+%27' . $id . '%27&sql_query=SELECT++%2A+%0AFROM++%60person%60+%0AWHERE+1++AND++%60id%60++%3D' . $id . '&goto=sql.php" target="_blank"><img border="0" src="icons/edit_sm.gif" alt="Add new ' . $whPar . '"></a>';
		$tpl->setVariable("AddSpouseNewBtn", $html) ;
	}
}

function paraEncode($text)
{
	global $mode;

	if ($mode == "r") {
		$text = str_replace("\n","<br>",$text);
	}
	return $text;
}


// MAIN

$edit_users = "test toms dad";  // list of users who can edit, space delimited

// CONNECT TO DB

$link = mysql_connect("localhost", "ftreeweb", "ftree_web")
   or die("Could not connect : " . mysql_error());
mysql_select_db("ftree",$link) or die("Could not select database");

// GET HTTP "GET" VARS

if ( isset($_GET['id']) ) {
        $id = $_GET['id'];
} else {                        
	$id = getLoginID();
}                               
$id=preg_replace("/[^0-9]/","",$id);  //get rid of anything but numbers
if ($id < 1 || $id > pow(2,17)) {
	die("ID is out of range.");
}

/* Modes: "r" = read only--display person
          "w" = write--edit person
	  "a" = add-create new person
*/

if ( isset($_GET['mode']) ) {
        $mode = $_GET['mode'];
} else {
        $mode = "r";
}

if ($mode == "a") {
	if (isset($_GET['rel'])) {
		$relation = $_GET['rel'];
	} else {
		$relation = "";
	}
	if (isset($_GET['fid'])) {
		$addFID = $_GET['fid'];
	} else {
		$addFID = "";
	}
	if (isset($_GET['mid'])) {
		$addMID = $_GET['mid'];
	} else {
		$addMID = "";
	}
} else {
	$relation = "";
}

// SET UP TEMPLATE

$isMobile = ChkIsMobile();
$tpl = new HTML_Template_IT("templates");
if ($mode == "w" || $mode == "a") {
	$isMobile ? $template = "person_frm_tmpl.html" : $template = "person_frm_tmpl.html"; //no mtemplate yet
} else {
	$isMobile ? $template = "person_mtmpl.html"     : $template = "person_tmpl.html";
}

$status = $tpl->loadTemplatefile($template, true, true);


// GET PERSON

if ($mode == "a") {
	$full = "";
	$sex = "";
	$idData['id'] = $id;
	$idData['first'] = "";
	$idData['middle'] = "";
	$idData['last'] = "";
	$idData['middle'] = "";
	$idData['last'] = "";
	$idData['suffix'] = "";
	$idData['nick'] = "";
	$idData['sex'] = "";
	$idData['dob'] = "";
	$idData['pob'] = "";
	$idData['birth'] = "";
	$fatherID = $addFID;
	$motherID = $addMID;
	$tpl->setVariable("AddFID", $addFID);
	$tpl->setVariable("AddMID", $addMID);
	if ($relation == "m") {
		$tpl->setVariable("GenderChkF", " checked");
	} elseif ($relation =="f") {
		$tpl->setVariable("GenderChkM", " checked");
	}
	$tpl->setVariable("stNoChgPar", "<!-- ");
	$tpl->setVariable("endNoChgPar", " -->");
} else {
	$query = "SELECT * FROM person WHERE `id` = $id";
	$result = mysql_query($query,$link) or die("Get person query failed : " . mysql_error());
	$idData = mysql_fetch_array($result, MYSQL_ASSOC);
	
	$full = formatName($idData['first'], $idData['middle'], $idData['last'], $idData['suffix'], $idData['nick'], "fnmls");
	$sex      = $idData['sex'];
	if ($sex == "M") {
		$tpl->setVariable("GenderChkM", " checked");
	} else {
		$tpl->setVariable("GenderChkF", " checked");
	}
	$fatherID = $idData['father'];
	$motherID = $idData['mother'];
}

$tpl->setVariable("PersonID", $idData['id']);
$tpl->setVariable("FullName", $full);
$tpl->setVariable("NFirst", $idData['first']);
$tpl->setVariable("NMiddle", $idData['middle']);
$tpl->setVariable("NLast", $idData['last']);
$tpl->setVariable("NSuffix", $idData['suffix']);
$tpl->setVariable("NNick", $idData['nick']);
if ($mode == "r") {
	$dob = formatDate($idData['dob'],"long");
} else {
	$dob = formatDate($idData['dob'],"short");
}
$tpl->setVariable("PersonSex", $idData['sex']);
$tpl->setVariable("DOB", $dob);
$tpl->setVariable("POB", $idData['pob']);
$tpl->setVariable("Birth", paraEncode($idData['birth']));
$dod = formatDate($idData['dod'],"long");
if ($mode == "r") {
	$dod = formatDate($idData['dod'],"long");
} else {
	$dod = formatDate($idData['dod'],"short");
}
$tpl->setVariable("DOD", $dod);
$tpl->setVariable("POD", $idData['pod']);
$tpl->setVariable("Death", paraEncode($idData['death']));
$tpl->setVariable("Mode", $mode);
$tpl->setVariable("Relation", $relation);

if ($mode != "a") {
	enableEdit($idData['id']);
	enableDBEdit($idData['id']);
	
	mysql_free_result($result);
} //during an add (at least an add child) we DO want to fill in parents
	
if ($mode != "a" || $relation == "c") {

	// GET PARENTS
	// don't come in here if adding a father or mother
	
	writeParent($fatherID, "Father");
	writeParent($motherID, "Mother");
}
	

if ($mode != "a") {                                                                                                                               
	
	// GET SPOUSE(S)
	
	if ( $sex == "M" ) {
		$query = "SELECT * FROM `marriage` WHERE `husband` = $id ORDER BY `date` ASC";
		$fID = $id;
	} else {
		$query = "SELECT * FROM `marriage` WHERE `wife`    = $id ORDER BY `date` ASC";
		$mID = $id;
	}
	
	$fndASpouse = false;
	$spResult = mysql_query($query,$link) or die("Query failed : " . mysql_error());
	
	while ($spData = mysql_fetch_array($spResult, MYSQL_ASSOC)) {
	
		$fndASpouse = true;
		if ( $sex == "M" ) {
			$spID = $spData['wife'];
			$mID  = $spID;
		} else {
			$spID = $spData['husband'];
			$fID  = $spID;
		}
	
		$query = "SELECT * FROM `person` WHERE `id` = $spID";
		$result = mysql_query($query,$link) or die("Query failed : " . mysql_error());
		$persData = mysql_fetch_array($result, MYSQL_ASSOC);
	
		$spFull = formatName($persData['first'], $persData['middle'], $persData['last'], $persData['suffix'], $persData['nick'], "fmls");
	        $dom = formatDate($spData['date'],"short");
	        if ($dom != "") {
	                $dom = " (m. $dom)";
	        }
	
		mysql_free_result($result);
	
	
	// GET CHILDREN
	
		writeKids($fID, $mID, "Child");
	
	// WRITE OUTER SPOUSE BLOCK
	
		$tpl->setCurrentBlock("Spouses") ;
		$tpl->setVariable("PersonID", $id) ;
		$tpl->setVariable("Spouse", $spFull) ;
		$tpl->setVariable("SpouseID", $spID) ;
		//$tpl->setVariable("PersonSex", $idData['sex']);
		$tpl->setVariable("SpMode", "edit") ;
		$tpl->setVariable("MarriageID", $spData['id']) ;
		if ($mode == "w") { $dformat = "short"; }
		else              { $dformat = "long" ; }
		$tpl->setVariable("DOM", formatDate($spData['date'],$dformat)) ;
		$tpl->setVariable("POM", $spData['place']) ;
		$tpl->setVariable("MNotes", paraEncode($spData['notes'])) ;
		enableAddChild($id,$fID,$mID);
		$tpl->parseCurrentBlock("Spouses") ;
	
	}

	enableAddSpouse();
	if (! $fndASpouse) {
	//if ( (! $fndASpouse) && ($mode == "a" || $mode == "w") ) {
	//if ($mode == "a" || $mode == "w") {
		$tpl->setCurrentBlock("Spouses") ;
		//$tpl->setVariable("PersonID", "") ;
		$tpl->setVariable("Spouse", "") ;
		$tpl->setVariable("SpouseID", "") ;
		$tpl->setVariable("SpMode", "add") ;
		$tpl->setVariable("MarriageID", "") ;
		$tpl->setVariable("DOM", "") ;
		$tpl->setVariable("POM", "") ;
		$tpl->setVariable("MNotes", "");
		$tpl->parseCurrentBlock("Spouses") ;	
	}
	
	
	//echo "</ol>\n\n";
	
	if ( $sex == "M" ) {
		$fID = $id;
		$mID = 0;
	} else {
		$fID = 0;
		$mID = $id;
	}
	
	writeKids($fID, $mID, "OthChild");
	
	mysql_free_result($spResult);
} else {
	$tpl->setVariable("StSkipSpouses",  "\n/\n<!-- \n") ;
	$tpl->setVariable("EndSkipSpouses", "\n-->\n\n") ;
}


// DONE -- CLEAN UP

mysql_close($link);

$tpl->setVariable("PersonID", $idData['id']);  //somehow it's getting lost
$tpl->show();

?>
